#!/data/Software/mydan/perl/bin/perl
use strict;
use warnings;
use FindBin qw( $RealBin );
use MYDan;
use MYDan::Util::OptConf;
use YAML::XS;
use Sys::Hostname;

=head1 SYNOPSIS

 $0 [--envname foo] 

=cut

my $option = MYDan::Util::OptConf->load();
my %o = $option->get( qw( envname=s ) )->dump();
$option->assert( 'envname' );

mkdir "$RealBin/../conf" unless -e "$RealBin/../conf";

my $Config = eval{ YAML::XS::LoadFile "$RealBin/../config/Config"; };
die "load config/Config fail:$@" if $@;
die "envname $o{envname} undef" unless $Config = $Config->{$o{envname}};

die "Config fail: $!" if system "$RealBin/Config --envname '$o{envname}'";

my $base = $RealBin;
$base =~ s#/[^/]+$##;

my $fileserverpath = '/data/glusterfs/fileserver';
unless( -e $fileserverpath )
{
    die "glusterfs: $!" if system( "mkdir '$fileserverpath'" );
}

map{
    die "$_ fail: $!" if system $_;
}(
    "mkdir -p /data/logs/JOB/task", 
    "ln -fsn /data/logs/JOB $base/logs",
    "ln -fsn $fileserverpath $base/fileserver",
);

my $mynamefile = '/etc/job.myip';

my $user = `id -un`;chop $user;
my $sudo = $user eq 'root' ? '' : 'sudo ';

my $hostname = Sys::Hostname::hostname;
if( -f "$MYDan::PATH/.open-c3.hostname" )
{
    $hostname = `cat $MYDan::PATH/.open-c3.hostname`;
    chomp $hostname;
    die "get hostname from .open-c3.hostname error" unless $hostname && $hostname =~ /^[a-zA-Z0-9_\.\-]+$/;
}

unless( -e $mynamefile )
{
    die "set job.myip fail:$!" if system( "${sudo}sh -c 'echo $hostname > $mynamefile'" ) 
}

my ( $exipfile, $inipfile ) = ( '/etc/job.exip', '/etc/job.inip' );
unless( -e $exipfile )
{
    die "nofind host info $hostname\n" unless my $myinfo = $Config->{host}{$hostname};
    my $exip = $myinfo->{exip} || $myinfo->{inip};
    my $inip = $myinfo->{inip} || $myinfo->{exip};
    
    $exip = $ENV{OPEN_C3_EXIP} if $ENV{OPEN_C3_EXIP};

    die "nofind exip" unless $exip && $exip =~ /^[0-9\.]+$/;
    die "nofind inip" unless $inip && $inip =~ /^[0-9\.]+$/;
    die "set job.myip fail:$!" if system( "${sudo}sh -c 'echo $exip > $exipfile'" );
    die "set job.myip fail:$!" if system( "${sudo}sh -c 'echo $inip > $inipfile'" );
}

die "cp nginx config fail: $!" if system "${sudo}cp $base/conf/*.open-c3.org.conf /etc/nginx/conf.d/";

die "reload nginx fail: $!" if system "${sudo}nginx -s reload";
